﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Security;

namespace IndyMosaic.Models.Blog
{
    [Bind(Include = "AuthorName,EmailAddress,Content,Subscribe")]
    public partial class Comment : Validatable
    {
        #region Properties
        public bool IsAuthorComment
        {
            get
            {
                string emailAddress = Membership.GetUser(Entry.UserID).Email;
                return emailAddress == EmailAddress;
            }
        }
        #endregion
        public void SetApprovalInfo(Guid userID, ApprovalStatus status)
        {
            ApprovalStatus = status;
            ApprovedByUserID = userID;
            ApprovedDate = DateTime.Now;
        }
        partial void OnCreated()
        {
            ApprovalStatus = ApprovalStatus.Pending;
            DatePosted = DateTime.MinValue;
        }
        partial void OnValidate(System.Data.Linq.ChangeAction action)
        {
            if (!IsValid)
            {
                throw new ApplicationException("Rule violations prevent saving");
            }
        }
        public override IEnumerable<RuleViolation> GetRuleViolations()
        {
            if (EntryID < 1)
            {
                yield return new RuleViolation("Comments must be associated to a valid blog entry.", "EntryID");
            }
            if (string.IsNullOrEmpty(AuthorName))
            {
                yield return new RuleViolation("Your name is required", "AuthorName");
            }
            if (Subscribe && !ValidEmailAddress(EmailAddress))
            {
                yield return new RuleViolation("If you subscribe for updates you must enter a valid email address", 
                    "EmailAddress");
            }
            if (string.IsNullOrEmpty(Content))
            {
                yield return new RuleViolation("Comments are no good if they don't say anything.", "Content");
            }
            if (DatePosted == DateTime.MinValue)
            {
                yield return new RuleViolation("You must set the date this comment is posted", "DatePosted");
            }
            if(string.IsNullOrEmpty(IPAddress))
            {
                yield return new RuleViolation("You must set the IP address of the commenter", "IPAddress");
            }
        }
    }
}
